package com.yonyou.jrmob.contacts.contact.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
import com.yonyou.jrmob.contacts.contact.dbhelper.DBManager_ct;
import com.yonyou.jrmob.contacts.contact.utils.CSIMCardUtil_ct;
import com.yonyou.jrmob.contacts.contact.view.dialog.MaterialDialog;

import java.util.List;

import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;

public class SortAdapter_ct extends BaseAdapter implements SectionIndexer{
	private List<ContactsVO_ct> list = null;
	private Context mContext;
	private DBManager_ct dbmr;
	private boolean flag;//是否需要排序
	private boolean hasSIMCard;
	public SortAdapter_ct(Context mContext, List<ContactsVO_ct> list, boolean flag) {
		this.mContext = mContext;
		this.list = list;
		this.flag = flag;
		dbmr = new DBManager_ct(mContext);
		hasSIMCard = new CSIMCardUtil_ct(mContext).isHasSIMCard();
	}
	
	/**
	 * @param list
	 */
	public void updateListView(List<ContactsVO_ct> list){
		this.list = list;
		notifyDataSetChanged();
	}

	public int getCount() {
		return this.list.size();
	}

	public ContactsVO_ct getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder = null;
		final ContactsVO_ct mContent = list.get(position);
		if (view == null) {
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.item_ct, null);
			viewHolder.point_quan = (TextView) view.findViewById(R.id.point_quan);
			viewHolder.tvTitle = (TextView) view.findViewById(R.id.title);
			viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);
			viewHolder.phoneView = (ImageView) view.findViewById(R.id.phone);
			viewHolder.messageView = (ImageView) view.findViewById(R.id.message);
			viewHolder.checkbox_quan = (CheckBox) view.findViewById(R.id.checkbox_quan);
			viewHolder.dept = (TextView) view.findViewById(R.id.contact_item_dept);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}

		viewHolder.checkbox_quan.setVisibility(View.GONE);
		if (flag == false){
			viewHolder.tvLetter.setVisibility(View.GONE);
		}else{
			int section = getSectionForPosition(position);
			if(position == getPositionForSection(section)){
				viewHolder.tvLetter.setVisibility(View.VISIBLE);
				viewHolder.tvLetter.setText(mContent.getSortLetters());
			}else{
				viewHolder.tvLetter.setVisibility(View.GONE);
			}
		}
		if (position % 5 == 0) {
			viewHolder.point_quan.setBackground(view.getResources().getDrawable(
					R.drawable.shape_red_ct)); // 前面的图片
		} else if (position % 5 == 1) {
			viewHolder.point_quan.setBackground(view.getResources().getDrawable(
					R.drawable.shape_blue_normal_ct)); // 前面的图片
		} else if (position % 5 == 2) {
			viewHolder.point_quan.setBackground(view.getResources().getDrawable(
					R.drawable.shape_00_ct)); // 前面的图片
		} else if (position % 5 == 3) {
			viewHolder.point_quan.setBackground(view.getResources().getDrawable(
					R.drawable.shape_1l_ct)); // 前面的图片
		} else if (position % 5 == 4) {
			viewHolder.point_quan.setBackground(view.getResources().getDrawable(
					R.drawable.shape_black_0f_ct)); // 前面的图片
		}
		String name = "";
		if (null != list.get(position)
				&& list.get(position).getContactName().length() > 2) {
			name = list
					.get(position)
					.getContactName()
					.substring(
							list.get(position).getContactName().length() - 2);
		} else {
			name = list.get(position).getContactName();
		}
		viewHolder.point_quan.setText(name);
		viewHolder.tvTitle.setText(this.list.get(position).getContactName());
		viewHolder.dept.setText(this.list.get(position).getGroupName());
		viewHolder.phoneView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//拨打电话
				final MaterialDialog dialog = new MaterialDialog(mContext);
				dialog.setTitle("拨打确认");
				dialog.setMessage(list.get(position).getContactName() + "\n" +
						list.get(position).getVdef());
				dialog.setPositiveButton("确认", new OnClickListener() {
					@Override
					public void onClick(View view) {
						dialog.dismiss();
						if(hasSIMCard){
							if(list.get(position).getVdef().toString().equals("")){
								//Toast.makeText(mContext,"未读取到电话号码",Toast.LENGTH_SHORT).show();

								AlertDialog.Builder builder=new AlertDialog.Builder(mContext);  //先得到构造器
								builder.setNegativeButton("未读取到电话号码!", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialogInterface, int i) {
										dialogInterface.dismiss();
									}
								}).create().show(); //设置内容

								return;
							}else{
								//判断在数据库中是否已经存在Yes：存在，NO：不存在
								dbmr.querychongfu(list.get(position).getContactName(), list.get(position).getVdef(), list.get(position).getContactTel(), list.get(position).getUser_email(), list.get(position).getCuserId());
								Intent intent = new Intent().setData(Uri.parse("tel:" + list.get(position).getVdef()));
								intent.setAction(Intent.ACTION_CALL);
								mContext.startActivity(intent);
							}

						}else{
							CommonUtil.showToast(mContext,"SIM卡未插入或暂时不可用!");
						}
					}
				});
				dialog.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View view) {
						dialog.dismiss();
					}
				});
				dialog.show();
				/*// 意图
		        Intent intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// 设置要拨打的号码
		        intent.setData(Uri.parse("tel:" + list.get(position).getVdef()));
		        // 设置动作,拨号 动作
		        //Intent.ACTION_DIAL  ACTION_CALL
		        intent.setAction(Intent.ACTION_DIAL);
		        // 跳转到拨号界面
		        mContext.startActivity(intent);  */
			}
		});

		/*跳转到发送短信页面
		Uri smsToUri = Uri.parse("smsto://10086");
		Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );
		startActivity( mIntent );

		发送邮件：
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.putExtra(Intent.EXTRA_EMAIL, address);
		intent.putExtra(Intent.EXTRA_SUBJECT, filename);
		intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filename)); ;
		intent.setType("text/csv");
		startActivity(Intent.createChooser(i, "EMail File"));*/

		viewHolder.messageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Uri smsToUri = Uri.parse("smsto:"+ list.get(position).getVdef());
				Intent intent = new Intent( Intent.ACTION_SENDTO, smsToUri );
				//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity( intent );
			}
		});
		return view;
		
	}

	final static class ViewHolder {
		TextView point_quan;
		TextView tvLetter;
		TextView tvTitle;
		ImageView phoneView;
		ImageView messageView;
		CheckBox checkbox_quan;
		TextView dept;
	}

	/**
	 * 
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		
		return -1;
	}
	
	/**
	 * 
	 * @return
	 */
	/*private String getAlpha(String str) {
		String  sortStr = str.trim().substring(0, 1).toUpperCase();
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}*/

	@Override
	public Object[] getSections() {
		return null;
	}
}